package com.itxiuyixiu.security.config;

import com.itxiuyixiu.security.service.AdminDetailsServiceImpl;
import com.itxiuyixiu.tools.security.handler.ApiLoginFailureHandler;
import com.itxiuyixiu.tools.security.handler.ApiLoginSuccessHandler;
import com.itxiuyixiu.tools.security.handler.ApiLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author 黄磊
 * @date 2020/5/1
 */
@Order(1)
@Configuration
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
    private final AdminDetailsServiceImpl adminDetialsService;
    private final ApiLoginSuccessHandler apiLoginSuccessHandler;
    private final ApiLoginFailureHandler apiLoginFailureHandler;
    private final ApiLogoutSuccessHandler apiLogoutSuccessHandler;

    public AdminSecurityConfig(AdminDetailsServiceImpl adminDetialsService, ApiLoginSuccessHandler apiLoginSuccessHandler, ApiLoginFailureHandler apiLoginFailureHandler, ApiLogoutSuccessHandler apiLogoutSuccessHandler) {
        this.adminDetialsService = adminDetialsService;
        this.apiLoginSuccessHandler = apiLoginSuccessHandler;
        this.apiLoginFailureHandler = apiLoginFailureHandler;
        this.apiLogoutSuccessHandler = apiLogoutSuccessHandler;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(adminDetialsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/admin/**")
                .formLogin()
                .successHandler(apiLoginSuccessHandler)
                .failureHandler(apiLoginFailureHandler)
                .loginPage("/admin/login.html")
                .loginProcessingUrl("/admin/login")
                .permitAll()
                .and()
                .logout().logoutUrl("/admin/logout").logoutSuccessHandler(apiLogoutSuccessHandler)
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }
}
